﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;

namespace RMS.Utils.EventAggregators
{
    public class DelegateReference : IDelegateReference

    {
        private readonly Delegate _delegate;
        private readonly Type _delegateType;
        private readonly MethodInfo _method;
        private readonly WeakReference _weakReference;

        // Methods
        public DelegateReference(Delegate @delegate, bool keepReferenceAlive)
        {
            if (keepReferenceAlive)
            {
                this._delegate = @delegate;
            }
            else
            {
                this._weakReference = new WeakReference(@delegate.Target);
                this._method = @delegate.Method;
                this._delegateType = @delegate.GetType();
            }
        }

        private Delegate TryGetDelegate()
        {
            if (this._method.IsStatic)
            {
                return Delegate.CreateDelegate(this._delegateType, null, this._method);
            }
            object target = this._weakReference.Target;
            if (target == null)
            {
                return null;
            }
            return Delegate.CreateDelegate(this._delegateType, target, this._method);
        }

        // Properties
        public Delegate Target
        {
            [DebuggerStepThrough]
            get
            {
                return (this._delegate ?? this.TryGetDelegate());
            }
        }
    }
}
